/*
 * Copyright (c) 2019.  鼎捷软件股份有限公司.All rights reserved.
 */

package com.digiwin.dap.middleware.service.impl;

import com.digiwin.dap.middleware.entity.AssociationEntity;
import com.digiwin.dap.middleware.service.AssociationEntityService;

import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 做级联删除定义，需要做级联删除的，需要往此服务中添加依赖关系
 */
@Service
public class AssociationEntityServiceImpl implements AssociationEntityService {

    private Map<String, List<AssociationEntity>> association = new HashMap<>();

    @Override
    public List<AssociationEntity> getAssociationEntities(String masterTable) {
        if (!association.containsKey(masterTable)) {
            List<AssociationEntity> associationEntities = new ArrayList<>();
            association.put(masterTable, associationEntities);
        }
        return association.get(masterTable);
    }

    /**
     * 添加关联表关系
     *
     * @param masterTable     主表
     * @param slaveTable      从表
     * @param foreignKey      外键
     * @param isCascadeDelete 是否级联删除，如果true，删除主表的时候，自动删除关联的数据，否则删除会做引用检查，一旦存在引用，禁止删除
     */
    @Override
    public void addAssociationEntities(String masterTable, String slaveTable, String foreignKey, boolean isCascadeDelete) {
        Assert.hasText(masterTable, "masterTable不能为空");
        Assert.hasText(slaveTable, "slaveTable不能为空");
        Assert.hasText(foreignKey, "foreignKey不能为空");
        List<AssociationEntity> associationEntities = getAssociationEntities(masterTable);
        associationEntities.add(new AssociationEntity(slaveTable, foreignKey, isCascadeDelete));
    }

//    /**
//     * 判断是否是死循环
//     *
//     * @param masterTable         主表
//     * @param slaveTable          从表
//     * @return
//     */
//    private boolean isEndless(String masterTable,String slaveTable){
//        List<AssociationEntity> associationEntities = getAssociationEntities(slaveTable);
//        if (associationEntities != null){
//            for (AssociationEntity as : associationEntities) {
//                if (masterTable.equals(as.getTableName())){
//                    return true;
//                }
//                return isEndless(masterTable,as.getTableName());
//            }
//        }
//        return false;
//    }
}
